﻿using System;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Runtime.Serialization;

namespace Portal.Data.Entity
{
    [Table(Name = "dbo.BookByAuthor"), Serializable, DataContract]
    public class BookByAuthor : BaseObject
    {
        #region Properties
        [Column(IsPrimaryKey = true)]
        public int AuthorId { get; set; }

        [Column]
        public string BookIds { get; set; }
        #endregion

        /// <summary>
        /// Chuyển book từ Author này sang Author khác
        /// </summary>
        /// <param name="bookId"></param>
        /// <param name="newAuthorId"></param>
        /// <param name="oldAuthorId"></param>
        public static void ChangedBookByAuthor(int bookId, int newAuthorId, int oldAuthorId = 0)
        {
            //remove older
            if (oldAuthorId > 0 && oldAuthorId != newAuthorId)
                RemoveBookByAuthor(oldAuthorId, bookId);

            //insert book into list by newAuthor
            using (var context = new CmsDataContext())
            {
                var bookids = context.BookByAuthors.Where(x => x.AuthorId == newAuthorId).Select(x => x.BookIds).FirstOrDefault();
                if (bookids != null)
                {
                    var full = "," + bookids + ",";
                    if (full.IndexOf("," + bookId + ",") < 0)
                    {
                        bookids += "," + bookId;
                        context.ExecuteCommand("update BookByAuthor set BookIds={0} where AuthorId={1}", bookids, newAuthorId);
                    }
                }
                else
                {
                    context.ExecuteCommand("INSERT BookByAuthor(AuthorId,BookIds) values({0},{1})", newAuthorId, bookId);
                }
            }
        }

        /// <summary>
        /// Xóa book khỏi danh sách theo Tác giả
        /// </summary>
        /// <param name="authorId"></param>
        /// <param name="bookId"></param>
        public static void RemoveBookByAuthor(int authorId, int bookId)
        {
            using (var context = new CmsDataContext())
            {
                var bookids = context.BookByAuthors.Where(x => x.AuthorId == authorId).Select(x => x.BookIds).FirstOrDefault();
                if (bookids != null)
                {
                    var bids =
                        bookids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToInt32(n))
                            .ToList();
                    if (bids.Contains(bookId))
                    {
                        bids.Remove(bookId);
                        bookids = string.Join(",", bids);   //new values
                        context.ExecuteCommand("update BookByAuthor set BookIds={0} where AuthorId={1}", bookids, authorId);
                    }
                }
            }
        }
    }
}
